# import the necessary packages
import json
import os
import random

import cv2 as cv
import keras.backend as K
import numpy as np
import scipy.io

from car_recognition.utils import load_model




def loadModel():
    # global cars_meta
    # global model
    current_path = os.path.dirname(__file__)
    cars_meta = scipy.io.loadmat(current_path + '/devkit/cars_meta')
    model = load_model()
    model.load_weights(current_path + '/models/model.24-0.99.hdf5')
    print("loadcompleted")
    return cars_meta,model




def getModel(path,cars_meta,model):
    try:
        img_width, img_height = 224, 224
        # model = load_model()
        current_path = os.path.dirname(__file__)
        # model.load_weights(current_path+'/models/model.24-0.99.hdf5')

        # cars_meta = scipy.io.loadmat(current_path+'/devkit/cars_meta')
        class_names = cars_meta['class_names']  # shape=(1, 196)
        class_names = np.transpose(class_names)
        test_path = 'data/test1/'
        filename = os.path.join(path)
        print('Start processing image: {}'.format(filename))
        bgr_img = cv.imread(filename)
        bgr_img = cv.resize(bgr_img, (img_width, img_height), cv.INTER_CUBIC)
        rgb_img = cv.cvtColor(bgr_img, cv.COLOR_BGR2RGB)
        rgb_img = np.expand_dims(rgb_img, 0)
        preds = model.predict(rgb_img)
        prob = np.max(preds)
        class_id = np.argmax(preds)
        text = ('Predict: {}, prob: {}'.format(class_names[class_id][0][0], prob))
        results = ({'Model': class_names[class_id][0][0], 'prob': '{:.4}'.format(prob)})
        print(results)
        with open(current_path+'/results.json', 'w') as file:
            json.dump(results, file, indent=4)

        # K.clear_session()
        # if results['prob']>0.4:
        return results['Model']
        # else:
        #     return results['Model']+"置信度较低"

    except Exception:
        print("检测完成")




def getModels(path):
    img_width, img_height = 224, 224
    model = load_model()
    current_path = os.path.dirname(__file__)
    model.load_weights(current_path+'/models/model.24-0.99.hdf5')

    cars_meta = scipy.io.loadmat(current_path+'/devkit/cars_meta')
    class_names = cars_meta['class_names']  # shape=(1, 196)
    class_names = np.transpose(class_names)
    # test_path = 'data/test1/'
    test_path=path
    test_images = [f for f in os.listdir(test_path) if
                   os.path.isfile(os.path.join(test_path, f)) and f.endswith(('.jpg','.png'))]
    samples = test_images
    results = []
    for i, image_name in enumerate(samples):
        filename = os.path.join(test_path, image_name)
        print('Start processing image: {}'.format(filename))
        bgr_img = cv.imread(filename)
        bgr_img = cv.resize(bgr_img, (img_width, img_height), cv.INTER_CUBIC)
        rgb_img = cv.cvtColor(bgr_img, cv.COLOR_BGR2RGB)
        rgb_img = np.expand_dims(rgb_img, 0)
        preds = model.predict(rgb_img)
        prob = np.max(preds)
        class_id = np.argmax(preds)
        text = ('Predict: {}, prob: {}'.format(class_names[class_id][0][0], prob))
        results.append({'label': class_names[class_id][0][0], 'prob': '{:.4}'.format(prob)})
        cv.imwrite(current_path+'/images/{}_out.png'.format(i), bgr_img)

    print(results)
    with open(current_path+'/results.json', 'w') as file:
        json.dump(results, file, indent=4)

    K.clear_session()

if __name__ == '__main__':
    # getModel("E:\\project1\\Car-Recognition\\data\\test1\\34.jpg")
    # getModels('data\\test1')
    # pass
    meta,model=loadModel()
    getModel('data/test1/20.jpg',meta,model)
    getModel('data/test1/20.jpg', meta, model)
    getModel('data/test1/20.jpg',meta,model)

